#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Seed的视图类
script name: views
Created on 2020/2/15 20:18 by PyCharm
@author: fujianjian
"""
from datetime import datetime

from flask import render_template, flash, redirect, url_for, request, jsonify

from .. import db, DEFAULT_PAGE_NO, DEFAULT_PAGE_SIZE, find_seed_queue
from ..model.seed import Production, Seed
from .forms import AddProductionForm, QueryProductionForm
from . import seed_blueprint


@seed_blueprint.route('/list/<pid>', methods=['post', 'get'])
def seed_list(pid):
    p = Production.query.filter(Production.id == pid).first()
    seed_page = Seed.query.filter(Seed.product_id == pid).paginate(DEFAULT_PAGE_NO, DEFAULT_PAGE_SIZE)
    return render_template('seed/list.html', seed_page=seed_page, product=p)


@seed_blueprint.route('/data', methods=['post', 'get'])
def seed_data():
    param = request.get_json()
    print('seed data param', param)
    seed_page = Seed.query.filter().paginate(param.get('pageno', DEFAULT_PAGE_NO)
                                             , param.get('pageSize', DEFAULT_PAGE_SIZE))
    res = {
        'code': 200,
        'msg': 'success',
        'data': {
            'total': seed_page.total,
            'total_page': seed_page.pages,
            'curr_page': seed_page.page,
            'page_size': seed_page.per_page,
            'contents': seed_page.items
        }
    }
    return jsonify(res)


@seed_blueprint.route('/productions', methods=['post', 'get'])
def production_list():
    form = QueryProductionForm()
    condition = set()
    if form.validate_on_submit():
        if form.name.data:
            condition.add(Production.name == form.name.data)
    page = Production.query.filter(*condition).paginate(1, 10)
    return render_template('seed/productions.html', productions_page=page, form=form)


@seed_blueprint.route('/film/data', methods=['post', 'get'])
def film_data():
    param = request.get_json()
    print('film data param', param)
    film_page = Production.query.filter().paginate(param.get('pageno', DEFAULT_PAGE_NO),
                                                   param.get('pageSize', DEFAULT_PAGE_SIZE))
    res = {
        'code': 200,
        'msg': 'success',
        'data': {
            'total': film_page.total,
            'total_page': film_page.pages,
            'curr_page': film_page.page,
            'page_size': film_page.per_page,
            'contents': film_page.items
        }
    }
    return jsonify(res)


@seed_blueprint.route('/addproduct', methods=['post', 'get'])
def add_production():
    form = AddProductionForm()
    if form.validate_on_submit():
        product = Production.query.filter_by(name=form.name.data).first()
        if product is None:
            product = Production(name=form.name.data,
                                 pub_time=form.pub_time.data,
                                 category=form.category.data,
                                 type=form.type.data,
                                 intro=form.intro.data,
                                 cover_uri=form.cover_uri.data,
                                 has_search=False, )
            db.session.add(product)
            db.session.commit()
            flash('add production success')
        else:
            flash('the production is exist, skip')
        return redirect(url_for('.production_list'))
    return render_template('seed/add_production.html', form=form)


@seed_blueprint.route('/modify/film', methods=['post', 'get'])
def modify_film():
    param = request.get_json()
    print('the request film json param', param)
    p = Production(name=param.get('name'),
                   pub_time=datetime.strptime(param['pub_time'], '%Y-%m-%d') if param[
                       'pub_time'] else datetime.utcnow(),
                   cover_uri=param.get('cover_uri', None),
                   type=param.get('type', None),
                   has_search=True if param['has_search'] and param['has_search'] == '1' else False)

    db.session.add(p)
    db.session.commit()
    res = {'code': 200, 'msg': 'success'}
    return jsonify(res)


@seed_blueprint.route('/find/seed/<pid>')
def search_production_seed(pid):
    product = Production.query.filter(Production.id == pid).first()
    find_seed_queue.put(product, block=True)
    flash('submit search seed task success')
    return redirect(url_for('.production_list'))
